package team.bluepen.supermarket.web.servlet;

import team.bluepen.supermarket.constant.Constant;
import team.bluepen.supermarket.constant.Error;
import team.bluepen.supermarket.data.entity.User;
import team.bluepen.supermarket.web.base.BaseServlet;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;

/**
 * 登录控制
 * @author Kai
 */
@WebServlet(name = "LoginControlServlet", urlPatterns = "/api/login-control")
public class LoginControlServlet extends BaseServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        super.doGet(req, resp);
    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String username = req.getParameter("username");
        String password = req.getParameter("password");
        HttpSession session = req.getSession();
        User user = new User()
                .setUsername(username)
                .setPassword(password)
                .build();

        Error error = userRepository.verifyUser(user);
        if (error.getState()) {
            session.setAttribute(Constant.SESSION_USER, user);
            resp.sendRedirect("/overview.jsp");
            return;
        }
        resp.sendRedirect("/?error=" + error.getValue());
    }

}
